// components/my-map/my-map.js
import regeneratorRuntime from '../../utils/runtime/runtime.js'
const fetch = require(`../../utils/fetch.js`);
const getLocation = require(`../../utils/getLocation.js`);
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
const qqmapsdk = new QQMapWX({
  key: 'JB3BZ-OLZCG-NSTQ2-IY7AB-LXSG2-SUFZN'
});
const config = require('../../config.js');
const Promisify = require('../../utils/util')//具体引入路径根据具体情况
const request = Promisify.wxPromisify(wx.request);//ajax请求

Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    controls: null,
    newWhere: "",
    addressInfo: {},
    latitude: 0,
    longitude: 0,
    flag: false,
    title: '',
    inputShowed: false,
    city: ''// 当前城市
  },
  /**
   * 生命周期
   */
  lifetimes: {
    
    ready: function() {
      //该函数获取所有栈内的路由
      let pages = getCurrentPages();
      //数组中最后一个即当前路由，options是参数
      let {options} = pages.pop();
      this.onLoadxxx(options || {})
    }
  },

  
  /**
   * 组件的方法列表
   */
  methods: {
    /**
     *  初始化函数
     */
    async onLoadxxx(options) {
      let that = this;
      // const res = await this.getLocationByCityInfo()
      // console.log(res);
      
      // 第一次进来只有城市没有默认坐标

      if (!options.latitude || !options.longitude) {

        const res = await wx.getLocation({type: 'gcj02'})

          // 获取地址
        fetch.showAddress(res.latitude, res.longitude, (newWhere, pois) => {
            let nowCity = pois[0].ad_info.city
            let cityRex = /县|市/g;
            //去掉县和市
            if (cityRex.test(nowCity)) {
              nowCity = nowCity.substring(0, nowCity.length - 1);
            }
            for (var i = 0; i < pois.length; i++) {
                //遍历数组 给数组元素加上隐藏
              pois[i].checked = false;
            }
            pois[0].checked = true;
            that.setData({
              pois: pois,
              nowCity: nowCity,
              totalCityName: pois[0].ad_info.city
            })
        });
    
        // wx.getLocation({
        //   type: 'wgs84',
        //   success(res) {
            that.setData({
              latitude: res.latitude,
              longitude: res.longitude,
              city: options.citys
            })

        //   }
        // })
      } else if(options.latitude && options.longitude) {// 选择完成后重新选择带初试坐标

        fetch.showAddress(options.latitude, options.longitude, (newWhere, pois) => {
          let nowCity = pois[0].ad_info.city
          let cityRex = /县|市/g;
          //去掉县和市
          if (cityRex.test(nowCity)) {
            nowCity = nowCity.substring(0, nowCity.length - 1);
          }
          for (var i = 0; i < pois.length; i++) {
            if(pois[i].location.lat == options.latitude && pois[i].location.lng == options.longitude && options.title == pois[i].title) {
              pois[i].checked = true;
            } else {
              pois[i].checked = false;

            }
          }
          that.setData({
            nowCity: nowCity,
            totalCityName: pois[0].ad_info.city,
            // title: options.title,
            pois: pois,

            latitude: options.latitude,
            longitude: options.longitude,
            flag: true,
            city: options.citys
          })
        });
      }


      let query = wx.createSelectorQuery().in(that);
        query.select('#map').boundingClientRect()
        query.exec(function (res) {
          that.setData({
            controls: [{
              id: 1,
              iconPath: `../../images/position.png`,
              position: {
                left: res[0].width / 2 - 25.5,
                top: res[0].height / 2 - 45,
                width: 50,
                height: 50
              },
              clickable: true
            },
            ]
          })
        })
    },

    // 根据城市名称查询城市详情

    async getLocationByCityInfo(city) {

      let mapApiUrl = `https://apis.map.qq.com/ws/geocoder/v1/`;
      const res = await request({
        url: mapApiUrl,
        data: {
          address: city,
          key: config.mapSecret
        },
        method: 'GET',
      })
      if (res.statusCode == 200 && res.data.status == 0) {
            const {location} = res.data.result
            return location
      }
      return null
    },
    /**
     * 视野发生变化
     */
    regionchange(e) {
      let that = this
      if (that.data.flag == false) {
        if (e.type == `end`) {
          that.mapCtx = wx.createMapContext(`map`);
          that.mapCtx.getCenterLocation({
            success: function (res) {
              // 获取地址

              fetch.showAddress(res.latitude, res.longitude, (newWhere, pois, addressInfo) => {
                console.log(newWhere);
              // 拖动时重新获取
              if((e.causedBy == 'scale' || e.causedBy == 'drag')) {
                for (var i = 0; i < pois.length; i++) {
                  pois[i].checked = false;
                }
                pois[0].checked = true;
                that.setData({
                  pois,
                })
              }
              that.setData({
                newWhere,
                addressInfo,
              })
              });
            }
          })
        }
      } else {
        that.setData({
          newWhere: that.data.title,
          flag: false
        })
      }
    },
    /**
     * 通过输入框改变地址时
     */
    chooseAddress(e) {
      let addressType = e.target.dataset.chooseaddress;
      let [longitude, latitude, endlongitude, endlatitude, goTime, goType, postGoTime]
        =
        [this.data.longitude, this.data.latitude];
      wx.navigateTo({
        url: `/components/my-chooseAddress/my-chooseAddress?addressType=${addressType}&longitude=${longitude}&latitude=${latitude}&city=${this.data.city}`,
      }) 
    },
    back: function() {
      const that = this
      let pages = getCurrentPages()
      let prevPage = pages[pages.length - 2]
      this.data.pois.forEach(function(v){
        if(v.checked == true){
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: v.location.lat,
              longitude: v.location.lng
            },
            success: function (res) {
              if(res.status === 0) {
                if(res.result.ad_info.city == that.data.city) {
                  const {adcode, district} = res.result.ad_info
                  let mapAddr = {
                    addressInfo: v.address,
                    newWhere: v.title,
                    latitude: v.location.lat,
                    longitude: v.location.lng,
                    district, // 所属区
                    adcode// 区编码
                  }
                  prevPage.setData({ mapAddr })
                  wx.navigateBack({
                    delta: 1
                  })
                } else { 
                  wx.showToast({
                    title: '请选择' + that.data.city + '内地址',
                    icon: 'none'
                  })
                }
              }
            }
        })
        }
      })
    },
    inputTyping: function (e) {
      this.setData({
        inputVal: e.detail.value
      });
    },

    // 触发regionchange  e.causedBy update
    checkedTap: function (e) {
      let that=this
      var pois = this.data.pois;
      var index=e.currentTarget.dataset.index
      let latitude = null, longitude = null
      //遍历当前数组
      for (let i = 0; i < pois.length; i++) {
        //判断数组是选中的 
        if (pois[i].checked == true) {
          pois[i].checked = !pois[i].checked
        }
        //当前点击的选中
        pois[index].checked = true
        latitude = pois[index].location.lat
        longitude = pois[index].location.lng
      }
      //从新遍历数组
      that.setData({
        pois: pois,
        latitude,
        longitude
      })
    },
    bindtap: function(e) {
      const that = this
      const {latitude, longitude} = e.detail

      fetch.showAddress(latitude, longitude, (newWhere, pois) => {
        console.log(newWhere, 'bindtap');
        let nowCity = pois[0].ad_info.city
        let cityRex = /县|市/g;
        //去掉县和市
        if (cityRex.test(nowCity)) {
          nowCity = nowCity.substring(0, nowCity.length - 1);
        }
        for (var i = 0; i < pois.length; i++) {
          pois[i].checked = false;
        }
        pois[0].checked = true;
        that.setData({
          totalCityName: pois[0].ad_info.city,
          nowCity: nowCity,
          pois: pois,
          latitude,
          longitude,
          newWhere,
        })
      });
    }
  },
})
